package me.keiwu.pub.util.excel;

import me.keiwu.pub.util.DateUtil;
import me.keiwu.pub.util.EntityUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by kei on 22/03/
 */
@Component
public class ExcelUtil {


    /**
     * 因为时间有限，随便写个超简单的导出
     * @param datas
     * @param <T>
     * @return
     */
    public <T> Workbook simpleExport(List<T> datas) {
        if (datas == null || datas.isEmpty()) return null;
        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet();
        boolean isHead = true;
        Row head = sheet.createRow(0);

        int row = 1;
        for (Object data : datas) {
            Row r = sheet.createRow(row++);
            this.setCell(EntityUtil.transBean2Map(data), head, r, isHead);
            isHead = false;
        }
        return wb;
    }



    public void setCell(Map<String, Object> data, Row headRow, Row contentRow, boolean isHead) {
        List<String> keyList = new ArrayList<>(data.keySet());
        Collections.sort(keyList);
        int index = 0;
        for (String s : keyList) {
            if (isHead) {
                Cell hc = headRow.createCell(index);
                hc.setCellValue(s);
            }
            Cell c = contentRow.createCell(index++);
            Object obj = data.get(s);
            if (obj == null) continue;
            if (obj instanceof Date) {
                c.setCellValue(DateUtil.formatDate((Date) obj, DateUtil.DEFAULT_PATTERN2));
            } else if (obj instanceof Map) {
                this.setCell((Map<String, Object>) obj, headRow, contentRow, isHead);
            } else {
                c.setCellValue("" + obj);
            }
        }

    }



    public void write(HttpServletResponse response, Workbook wb, String fileName) throws IOException {
        response.reset();
        response.setContentType("application/octet-stream; charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename="+response.encodeRedirectURL(fileName));
        wb.write(response.getOutputStream());
    }



    public static void main(String[] args) {
    }


}
